import './limit.scss'
import { useEffect, useState } from 'react'
import { Form, Input, Tooltip, Table, Pagination, Button, Radio, message } from 'antd'
import { EditOutlined } from '@ant-design/icons'
import {
  reqAdminGetAllAuthority,
  reqAdminUpdateUserAuthority,
  reqAdminGetAllUser,
} from '@/api/admin'

function Limit() {
  const [edit, setEdit] = useState(false)
  const [pageSize, setPageSize] = useState(5)
  const [pageNo, setPageNo] = useState(1)
  const [userInfo, setUserInfo] = useState<any>([])
  const [total, setTotal] = useState(0)
  const [formData, setFormData] = useState<any>({})
  const [history, setHistory] = useState<any>({})
  const [form] = Form.useForm()

  useEffect(() => {
    getAllAuthority()
  }, [pageNo, pageSize])

  // 获取权限表
  const getAllAuthority = async () => {
    Promise.all([
      reqAdminGetAllUser({ pageNO: 1, pageSize: 999999 }),
      reqAdminGetAllAuthority({ pageNO: pageNo, pageSize }),
    ]).then((res: any) => {
      if (!(res[0].code === 200 && res[1].code === 200)) return
      const data1 = res[0].data.records.map((item: any) => ({
        id: item.id,
        username: item.username,
      }))
      // 根据otherData来遍历并匹配融合数据
      const mergedData = res[1].data.records
        .map((data: any) => {
          // 找到匹配的users项
          const match = data1.find((user: any) => user.id === data.userId)
          // 如果找到匹配项，则合并数据
          if (match) {
            return { ...match, ...data }
          }
          // 如果没有匹配项，则返回原始otherData数据
          return data
        })
        .map((item: any) => ({
          ...item,
          key: item.id,
        }))
      setTotal(res[1].data.total)
      setUserInfo(mergedData)
    })
  }
  // 修改用户权限
  const updateUserAuthority = async () => {
    const newFormData = { ...formData, id: formData.userId }
    const res: any = await reqAdminUpdateUserAuthority(newFormData)
    if (res.code === 200) {
      getAllAuthority()
      setEdit(false)
      message.success('修改成功！')
    }
  }

  useEffect(() => {
    if (edit) {
      form.setFieldsValue(formData)
    }
  }, [edit, formData, form])

  const columns: any = [
    {
      title: '学生Id',
      width: 100,
      align: 'center',
      ellipsis: true,
      dataIndex: 'id',
    },
    {
      title: '姓名',
      align: 'center',
      ellipsis: true,
      dataIndex: 'username',
    },
    {
      title: '大模型权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'module',
      render: (text: any) => (text === 1 ? '有' : '无'),
    },
    {
      title: '文本权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'text',
      render: (text: any) => (text === 1 ? '有' : '无'),
    },
    {
      title: '选课权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'choose',
      render: (text: any) => (text === 1 ? '有' : '无'),
    },
    {
      title: '模拟面试权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'interview',
      render: (text: any) => (text === 1 ? '有' : '无'),
    },
    {
      title: '修改',
      width: 150,
      align: 'center',
      key: 'action',
      render: (data: any) => (
        <Tooltip title="修改信息">
          <Button
            ghost
            type="primary"
            shape="circle"
            onClick={() => {
              setEdit(true)
              setFormData(data)
              setHistory(data)
            }}
            icon={<EditOutlined />}
          ></Button>
        </Tooltip>
      ),
    },
  ]

  const onShowSizeChange = (_: number, size: number) => {
    setPageSize(size)
  }

  const handleChange = (page: number) => {
    setPageNo(page)
  }

  // 表单提交
  const onFinish = async () => {
    await form.validateFields()
    updateUserAuthority()
  }

  // 点击重置按钮的回调
  const handleReset = () => {
    setFormData(history)
  }

  return (
    <div className="Limit">
      {!edit ? (
        <>
          <Table columns={columns} dataSource={userInfo} pagination={false} />
          <Pagination
            style={{ marginTop: '20px' }}
            pageSizeOptions={['3', '5', '7', '10']}
            showSizeChanger
            defaultPageSize={pageSize}
            onChange={handleChange}
            onShowSizeChange={onShowSizeChange}
            total={total}
            align="end"
          />
        </>
      ) : (
        <div className="form">
          <div className="form-content">
            <Form
              form={form}
              name="basic"
              size="large"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 24 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              autoComplete="off"
            >
              <Form.Item label="用户ID" name="userId">
                <Input disabled autoComplete="off" />
              </Form.Item>
              <Form.Item label="大模型权限" name="module">
                <Radio.Group
                  value={formData.module}
                  onChange={(e) => setFormData({ ...formData, module: e.target.value })}
                >
                  <Radio value={1}>允许</Radio>
                  <Radio value={0}>禁止</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="文本权限" name="text">
                <Radio.Group
                  value={formData.text}
                  onChange={(e) => setFormData({ ...formData, text: e.target.value })}
                >
                  <Radio value={1}>允许</Radio>
                  <Radio value={0}>禁止</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="选课权限" name="choose">
                <Radio.Group
                  value={formData.choose}
                  onChange={(e) => setFormData({ ...formData, choose: e.target.value })}
                >
                  <Radio value={1}>允许</Radio>
                  <Radio value={0}>禁止</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="模拟面试权限" name="interview">
                <Radio.Group
                  value={formData.interview}
                  onChange={(e) => setFormData({ ...formData, interview: e.target.value })}
                >
                  <Radio value={1}>允许</Radio>
                  <Radio value={0}>禁止</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button onClick={handleReset}>重置</Button>
                <Button
                  style={{ margin: '0 20px' }}
                  onClick={() => {
                    form.resetFields()
                    setEdit(false)
                  }}
                >
                  退出
                </Button>
                <Button type="primary" onClick={onFinish}>
                  确定
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      )}
    </div>
  )
}

export default Limit
